package com.akupilih.app;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.akupilih.app.entity.E_Candidate;
import com.akupilih.app.entity.E_Event;
import com.akupilih.app.entity.E_Janji;
import com.akupilih.app.entity.E_Organisasi;
import com.akupilih.app.entity.E_Pekerjaan;
import com.akupilih.app.entity.E_Pendidikan;
import com.akupilih.app.entity.E_Penghargaan;
import com.akupilih.app.helper.DateHelper;
import com.akupilih.app.helper.JSONHelper;
import com.akupilih.app.helper.VolleyHelper;
import com.akupilih.app.model.DBClass;
import com.akupilih.app.model.Utils;
import com.akupilih.app.model.WebService;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

public class SplashActivity extends Activity {

	protected int _splashTime = 3000;
	protected int _splashTime2 = 15000;
	private Thread splashTread;
	private String TAG = "Splash";
	DBClass db = new DBClass(SplashActivity.this);
	String id_candidate;
	TextView message;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		ImageView image = (ImageView) findViewById(R.id.fragment_welcome_app_name);
		Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_PARENT, 5.0f, Animation.RELATIVE_TO_SELF,
				0.0f);
		anim.setDuration(1000);
		anim.setFillAfter(true);
		image.startAnimation(anim);
		image.setImageResource(R.drawable.ic_app_name);
		message = (TextView) findViewById(R.id.activity_splash_message);

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		final SplashActivity sPlashScreen = this;

		// thread for displaying the SplashScreen
		splashTread = new Thread() {
			@Override
			public void run() {
				try {
					synchronized (this) {

						if (db.getIsPertama()) {
							if (!isNetworkConnected()) {
								message.setText("Ooooops... gagal karena tidak ada koneksi :(");
							}
							new DoingAllThreads().execute();
							wait(_splashTime2);
						} else {
							String URL4 = WebService.EVENT();
							getEvent(SplashActivity.this, URL4);
							wait(_splashTime);
						}

					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					Intent i = new Intent();
					if (db.getIsPertama()) {
						if (isNetworkConnected()) {
							i.setClass(SplashActivity.this,
									WelcomeActivity.class);
							startActivity(i);
							finish();
						} else {
							SplashActivity.this.finish();
						}
					} else {
						i.setClass(SplashActivity.this, MainActivity.class);
						startActivity(i);
						finish();
					}

				}
			}
		};

		splashTread.start();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
				message.setText("yang sabar yaaa.. internet cepat buat apa?");
		}
		return true;
	}

	public void getBerita(final Context contex, String URL) {
		JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
				URL, null, new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject obj) {

						try {
							JSONArray root = obj.getJSONArray("posts");
							JSONHelper.getBerita(root, contex);
						} catch (JSONException e) {
							ACRAPostSender.TRACE(TAG + " ERROR", "getData : "
									+ e.getMessage());
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						// TODO Auto-generated method stub
						ACRAPostSender.TRACE(TAG
								+ ".getData(...).new ErrorListener() {...}",
								"onErrorResponse : " + error.toString());
						VolleyHelper.showVolleyError(contex, error);
					}
				});
		BaseApplication.getInstance().addToRequestQueue(request, TAG);
	}

	public void getJanji(final Context contex, String URL) {
		JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
				URL, null, new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject obj) {

						try {
							JSONObject data = obj.getJSONObject("data");
							JSONObject result = data.getJSONObject("results");
							JSONArray event = result.getJSONArray("promises");
							for (int i = 0; i < event.length(); i++) {
								JSONObject get = event.getJSONObject(i);
								E_Janji jan = new E_Janji();
								jan.setId_calon(get.getString("id_calon"));
								jan.setContext_janji(get
										.getString("context_janji"));
								jan.setJanji(get.getString("janji"));
								jan.setTanggal(DateHelper.convertDateNoTime(get
										.getString("tanggal")));
								jan.setJudul_sumber(get
										.getString("judul_sumber"));
								db.insertJanji(jan);
							}
						} catch (JSONException e) {
							ACRAPostSender.TRACE(TAG + " ERROR", "getData : "
									+ e.getMessage());
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						// TODO Auto-generated method stub
						ACRAPostSender.TRACE(TAG
								+ ".getData(...).new ErrorListener() {...}",
								"onErrorResponse : " + error.toString());
						VolleyHelper.showVolleyError(contex, error);
					}
				});
		BaseApplication.getInstance().addToRequestQueue(request, TAG);
	}

	public void getEvent(final Context contex, String URL) {
		JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
				URL, null, new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject obj) {

						try {
							JSONObject data = obj.getJSONObject("data");
							JSONObject result = data.getJSONObject("results");
							JSONArray event = result.getJSONArray("events");
							for (int i = 0; i < event.length(); i++) {
								JSONObject get = event.getJSONObject(i);
								E_Event ev = new E_Event();
								ev.setId(Integer.parseInt(get.getString("id")));
								ev.setJudul(get.getString("judul"));
								ev.setDeskripsi(get.getString("deskripsi"));
								ev.setTanggal_mulai(DateHelper
										.convertDateNoTime(get
												.getString("tanggal_mulai")));
								ev.setWaktu_mulai(get.getString("waktu_mulai"));
								db.insertEvent(ev);
							}
						} catch (JSONException e) {
							ACRAPostSender.TRACE(TAG + " ERROR", "getData : "
									+ e.getMessage());
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						// TODO Auto-generated method stub
						ACRAPostSender.TRACE(TAG
								+ ".getData(...).new ErrorListener() {...}",
								"onErrorResponse : " + error.toString());
						VolleyHelper.showVolleyError(contex, error);
					}
				});
		BaseApplication.getInstance().addToRequestQueue(request, TAG);
	}

	// PARSING PEMILU APP CANDIDATE
	public void getPResidential(final Context contex, String URL) {
		JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
				URL, null, new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject obj) {

						try {
							JSONObject data = obj.getJSONObject("data");
							JSONObject result = data.getJSONObject("results");
							JSONArray caleg = result.getJSONArray("caleg");
							for (int i = 0; i < caleg.length(); i++) {
								JSONObject profil = caleg.getJSONObject(i);
								id_candidate = profil.getString("id");
								Log.d("nama caleg ->", profil.getString("nama"));
								E_Candidate cand = new E_Candidate();
								cand.setId(id_candidate);
								cand.setNama(profil.getString("nama"));
								cand.setRole(profil.getString("role"));
								cand.setJenis_kelamin(profil
										.getString("jenis_kelamin"));
								cand.setAgama(profil.getString("agama"));
								cand.setTempat_lahir(profil
										.getString("tempat_lahir"));
								cand.setTgl_lahir(DateHelper
										.convertDateNoTime(profil
												.getString("tanggal_lahir")));
								cand.setStatus_perkawinan(profil
										.getString("status_perkawinan"));
								cand.setNama_pasangan(profil
										.getString("nama_pasangan"));
								cand.setJumlah_anak(String.valueOf(profil
										.getInt("jumlah_anak")));
								cand.setKelurahan(profil
										.getString("kelurahan_tinggal"));
								cand.setKecamatan(profil
										.getString("kecamatan_tinggal"));
								cand.setKabupaten(profil
										.getString("kab_kota_tinggal"));
								cand.setProvinsi(profil
										.getString("provinsi_tinggal"));
								cand.setBiografi(profil.getString("biografi"));
								db.insertCandidate(cand);
								JSONArray pendidikan = profil
										.getJSONArray("riwayat_pendidikan");
								for (int j = 0; j < pendidikan.length(); j++) {
									JSONObject pObj = pendidikan
											.getJSONObject(j);
									E_Pendidikan pend = new E_Pendidikan();
									pend.setId(pObj.getInt("id"));
									pend.setId_candidate(id_candidate);
									pend.setRingkasan(pObj
											.getString("ringkasan"));
									pend.setTgl_mulai(pObj
											.getString("tanggal_mulai"));
									pend.setTgl_selesai(pObj
											.getString("tanggal_selesai"));
									db.insertPendidikan(pend);
								}
								JSONArray pekerjaan = profil
										.getJSONArray("riwayat_pekerjaan");
								for (int j = 0; j < pekerjaan.length(); j++) {
									JSONObject jobj = pekerjaan
											.getJSONObject(j);
									E_Pekerjaan pek = new E_Pekerjaan();
									pek.setId(jobj.getInt("id"));
									pek.setId_candidate(id_candidate);
									pek.setRingkasan(jobj
											.getString("ringkasan"));
									pek.setTgl_mulai(jobj
											.getString("tanggal_mulai"));
									pek.setTgl_selsai(jobj
											.getString("tanggal_selesai"));
									db.insertPekerjaan(pek);
								}

								JSONArray organisasi = profil
										.getJSONArray("riwayat_organisasi");
								for (int j = 0; j < organisasi.length(); j++) {
									JSONObject joo = organisasi
											.getJSONObject(j);
									E_Organisasi org = new E_Organisasi();
									org.setId(joo.getInt("id"));
									org.setId_candidate(id_candidate);
									org.setJabatan(joo.getString("jabatan"));
									org.setRingkasan(joo.getString("ringkasan"));
									org.setTgl_mulai(joo
											.getString("tanggal_mulai"));
									org.setTgl_selesai(joo
											.getString("tanggal_selesai"));

									db.insertOrganisasi(org);
								}
								JSONArray peng = profil
										.getJSONArray("riwayat_penghargaan");
								for (int j = 0; j < peng.length(); j++) {
									JSONObject jop = peng.getJSONObject(j);
									E_Penghargaan p = new E_Penghargaan();
									p.setId(jop.getInt("id"));
									p.setId_candidate(id_candidate);
									p.setInstitusi(jop.getString("institusi"));
									p.setRingkasan(jop.getString("ringkasan"));
									p.setTgl(jop.getString("tanggal"));
									db.insertPenghargaan(p);
								}

							}

						} catch (JSONException e) {
							ACRAPostSender.TRACE(TAG + " ERROR", "getData : "
									+ e.getMessage());
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						// TODO Auto-generated method stub
						ACRAPostSender.TRACE(TAG
								+ ".getData(...).new ErrorListener() {...}",
								"onErrorResponse : " + error.toString());
						VolleyHelper.showVolleyError(contex, error);
					}
				});
		BaseApplication.getInstance().addToRequestQueue(request, TAG);
	}

	private boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni == null) {
			// There are no active networks.
			return false;
		} else
			return true;
	}

	class DoingAllThreads extends AsyncTask<Void, Integer, String> {
		protected void onPreExecute() {
			Log.d("PreExceute", "On pre Exceute......");
		}

		protected String doInBackground(Void... arg0) {
			this.cancel(false);
			
			Log.d("DoINBackGround", "On doInBackground...");
			String URL = WebService.BERITA();
			String URL2 = WebService.PRESIDENTIAL_CANDIDATE();
			String URL3 = WebService.JANJI();
			String URL4 = WebService.EVENT();
			getBerita(SplashActivity.this, URL);
			getPResidential(SplashActivity.this, URL2);
			getJanji(SplashActivity.this, URL3);
			getEvent(SplashActivity.this, URL4);
			
			return "You are at PostExecute";
		}

		protected void onProgressUpdate(Integer... a) {
			Log.d("You are in progress update ... ", "" + a[0]);
		}

		protected void onPostExecute(String result) {
			Log.d("", "" + result);
		}
	}

}
